package com.yt.common.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据库表结构导出工具类
 *
 * @author 
 * @Date 2025-11-13
 */
@Component
public class TableStructureExportUtils {

    @Autowired
    private TableStructureUtils tableStructureUtils;

    /**
     * 导出表结构到Excel
     *
     * @param tableName 表名
     * @param response  HttpServletResponse
     * @throws IOException
     * @throws SQLException
     */
    public void exportTableStructureToExcel(String tableName, HttpServletResponse response) throws IOException, SQLException {
        // 设置响应头
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(tableName + "_结构信息.xls", "utf-8"));
        
        // 获取表结构信息
        List<Map<String, Object>> structureList = tableStructureUtils.getTableStructure(tableName);
        
        // 创建Excel数据
        List<Map<String, Object>> exportList = new ArrayList<>();
        for (Map<String, Object> map : structureList) {
            Map<String, Object> exportMap = new HashMap<>();
            exportMap.put("列名", map.get("columnName"));
            exportMap.put("数据类型", map.get("typeName"));
            exportMap.put("列大小", map.get("columnSize"));
            exportMap.put("是否可为空", map.get("nullable"));
            exportMap.put("列注释", map.get("remarks"));
            exportMap.put("默认值", map.get("columnDef"));
            exportMap.put("列序号", map.get("ordinalPosition"));
            exportList.add(exportMap);
        }
        
        // 导出Excel
        Workbook workbook = ExcelExportUtil.exportExcel(exportList, ExcelType.HSSF);
        workbook.write(response.getOutputStream());
        workbook.close();
    }
}